﻿
#region 程序集引用区
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using SubSonic.DataProviders;
using SubSonic.Extensions;
using System.Linq.Expressions;
using SubSonic.Schema;
using System.Collections;
using SubSonic;
using SubSonic.Repository;
using System.ComponentModel;
using System.Data.Common;
using SubSonic.Query;
using System.Xml;
using System.Xml.Serialization;
using System.Reflection;
#endregion

namespace eTerm.MsSql.DbProvider{
    
    /// <summary>
    /// 文 件 名: PnrPassenger.cs
    /// CLR版本 : v2.0.50727
    /// 作   者 : lijun.hu
    /// 版    权: Copyright @2011 lijun.hu(FORCEN HU) 
    /// 电子邮箱：lijun.hu@shinsoft.net
    /// 说    明: 未定义
    /// 生成日期: 2013年8月2日
    /// </summary>
    [Serializable]
    public partial class PnrPassenger:IActiveRecord{
        
        #region 变量定义
        private bool isLoaded=false;
        private bool isNew=false;
        private List<IColumn> dirtyColumns;
        IRepository< PnrPassenger > _repo;
        ITable tbl;
        private static IQuerySurface _db;
        #endregion
        
        #region 构造函数
        /// <summary>
        /// 初始化一个新实例 <see cref="PnrPassenger"/>.
        /// <param name="dbProvider">采用注入式数据库配置初始化.</param>
        /// </summary>
        public PnrPassenger(IQuerySurface dbProvider){
            if (dbProvider != null) {
                _db = dbProvider;
                Init();
            }
        }
        
        /// <summary>
        /// 初始化一个新实例 <see cref="PnrPassenger"/>.
        /// </summary>
        public PnrPassenger(){
            if(_db==null)
                _db = Context.Instance.DbProvider;
            if(_db!=null)
                Init();
        }
        
        
        /// <summary>
        /// 实例内部初始化逻辑.
        /// </summary>
        void Init(){
            _repo = new SubSonicRepository< PnrPassenger >(_db);
            tbl=_repo.GetTable();
            dirtyColumns=new List<IColumn>();
            SetIsNew(true);     
        }
        #endregion
        
        #region 生成IRepository
        internal static IRepository< PnrPassenger > GetRepo(){
            if (_db == null)
                _db = Context.Instance.DbProvider;
            IRepository< PnrPassenger > _repo;
            _repo = new SubSonicRepository< PnrPassenger >(_db);
            return _repo;         
        }       
        #endregion
        
        #region PnrPassenger属性列表
        System.Int64 m_Id;
        /// <summary>
        /// 未定义
        ///</summary>
        [XmlAttribute()]
        public System.Int64  Id
        {
            get { return m_Id; }
            set
            {
                if(m_Id!=value)
                {
                    m_Id=value;
                    var col=tbl.Columns.FirstOrDefault(x=>x.PropertyName.ToLower()=="Id".ToLower());
                    if(col!=null){
                        if(!dirtyColumns.Any(x=>x.Name.ToLower()==col.Name.ToLower()) && isLoaded){
                            dirtyColumns.Add(col);
                        }
                    }
                }
            }
        }
        
        System.String m_PassengerName;
        /// <summary>
        /// 未定义
        ///</summary>
        [XmlAttribute()]
        public System.String  PassengerName
        {
            get { return m_PassengerName; }
            set
            {
                if(m_PassengerName!=value)
                {
                    m_PassengerName=value;
                    var col=tbl.Columns.FirstOrDefault(x=>x.PropertyName.ToLower()=="PassengerName".ToLower());
                    if(col!=null){
                        if(!dirtyColumns.Any(x=>x.Name.ToLower()==col.Name.ToLower()) && isLoaded){
                            dirtyColumns.Add(col);
                        }
                    }
                }
            }
        }
        
        System.String m_IdentityNo;
        /// <summary>
        /// 未定义
        ///</summary>
        [XmlAttribute()]
        public System.String  IdentityNo
        {
            get { return m_IdentityNo; }
            set
            {
                if(m_IdentityNo!=value)
                {
                    m_IdentityNo=value;
                    var col=tbl.Columns.FirstOrDefault(x=>x.PropertyName.ToLower()=="IdentityNo".ToLower());
                    if(col!=null){
                        if(!dirtyColumns.Any(x=>x.Name.ToLower()==col.Name.ToLower()) && isLoaded){
                            dirtyColumns.Add(col);
                        }
                    }
                }
            }
        }
        
        System.Int32 m_PassengerType;
        /// <summary>
        /// 未定义
        ///</summary>
        [XmlAttribute()]
        public System.Int32  PassengerType
        {
            get { return m_PassengerType; }
            set
            {
                if(m_PassengerType!=value)
                {
                    m_PassengerType=value;
                    var col=tbl.Columns.FirstOrDefault(x=>x.PropertyName.ToLower()=="PassengerType".ToLower());
                    if(col!=null){
                        if(!dirtyColumns.Any(x=>x.Name.ToLower()==col.Name.ToLower()) && isLoaded){
                            dirtyColumns.Add(col);
                        }
                    }
                }
            }
        }
        
        System.DateTime? m_Birthday;
        /// <summary>
        /// 未定义
        ///</summary>
        [XmlAttribute()]
        public System.DateTime?  Birthday
        {
            get { return m_Birthday; }
            set
            {
                if(m_Birthday!=value)
                {
                    m_Birthday=value;
                    var col=tbl.Columns.FirstOrDefault(x=>x.PropertyName.ToLower()=="Birthday".ToLower());
                    if(col!=null){
                        if(!dirtyColumns.Any(x=>x.Name.ToLower()==col.Name.ToLower()) && isLoaded){
                            dirtyColumns.Add(col);
                        }
                    }
                }
            }
        }
        
        System.Int32 m_IdentityType;
        /// <summary>
        /// 未定义
        ///</summary>
        [XmlAttribute()]
        public System.Int32  IdentityType
        {
            get { return m_IdentityType; }
            set
            {
                if(m_IdentityType!=value)
                {
                    m_IdentityType=value;
                    var col=tbl.Columns.FirstOrDefault(x=>x.PropertyName.ToLower()=="IdentityType".ToLower());
                    if(col!=null){
                        if(!dirtyColumns.Any(x=>x.Name.ToLower()==col.Name.ToLower()) && isLoaded){
                            dirtyColumns.Add(col);
                        }
                    }
                }
            }
        }
        
        System.Int64? m_TicketNoId;
        /// <summary>
        /// 未定义
        ///</summary>
        [XmlAttribute()]
        public System.Int64?  TicketNoId
        {
            get { return m_TicketNoId; }
            set
            {
                if(m_TicketNoId!=value)
                {
                    m_TicketNoId=value;
                    var col=tbl.Columns.FirstOrDefault(x=>x.PropertyName.ToLower()=="TicketNoId".ToLower());
                    if(col!=null){
                        if(!dirtyColumns.Any(x=>x.Name.ToLower()==col.Name.ToLower()) && isLoaded){
                            dirtyColumns.Add(col);
                        }
                    }
                }
            }
        }
        
        System.Int64? m_RequireId;
        /// <summary>
        /// 未定义
        ///</summary>
        [XmlAttribute()]
        public System.Int64?  RequireId
        {
            get { return m_RequireId; }
            set
            {
                if(m_RequireId!=value)
                {
                    m_RequireId=value;
                    var col=tbl.Columns.FirstOrDefault(x=>x.PropertyName.ToLower()=="RequireId".ToLower());
                    if(col!=null){
                        if(!dirtyColumns.Any(x=>x.Name.ToLower()==col.Name.ToLower()) && isLoaded){
                            dirtyColumns.Add(col);
                        }
                    }
                }
            }
        }
        
        #endregion
        
        #region 修改属性
        /// <summary>
        /// 设置该记录为新数据(供Save方法判断为Insert或Update)
        ///</summary>
        public void SetIsNew(bool isNew){
            this.isNew=isNew;
            this.isLoaded = !isNew;
        }
        
        /// <summary>
        /// 设置该记录是否从数据读取
        ///</summary>
        public void SetIsLoaded(bool isLoaded){
            this.isLoaded=isLoaded;
            this.isNew = !isLoaded;
        }
        
        /// <summary>
        /// 设置数据访问接口
        ///</summary>
        public void SetDbProvider(IQuerySurface dbProvider){
            _db=dbProvider;
            Init();
        }
        #endregion
        
        #region 获取属性
        /// <summary>
        /// 获取该记录是否从数据读取
        ///</summary>
        public bool IsLoaded(){
            return isLoaded;
        }
        
        /// <summary>
        /// 实体中是否含有可更新属性
        ///</summary>
        public bool IsDirty(){
            return dirtyColumns.Count>0;
        }
        
        /// <summary>
        /// 实体是否为新实体
        ///</summary>
        public bool IsNew(){
            return isNew;
        }
        
        /// <summary>
        /// 获取所有可更新属性集合
        ///</summary>
        public List<IColumn> GetDirtyColumns (){
            return dirtyColumns;
        }
        
        /// <summary>
        /// 获取Mapping表所有数据列
        ///</summary>
        [Browsable(false)]
        [XmlIgnore()]
        public IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }
        #endregion    
        
        #region 主键相关
        /// <summary>
        /// 获取表主键（不能使用组合主键）
        ///</summary>
        public string KeyName()
        {
            return "Id";
        }

        /// <summary>
        /// 获取表主键值
        ///</summary>
        public object KeyValue()
        {
            return this.Id;
        }
        
        /// <summary>
        /// 设置主键值
        ///</summary>
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo< System.Int64 >();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        /// <summary>
        /// 主键ToString()
        ///</summary>
        public override string ToString(){
            return this.Id.ToString();
        }
        
        
        /// <summary>
        /// Returns a hash code for this instance.
        /// </summary>
        /// <returns>
        /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. 
        /// </returns>
        public override int GetHashCode() {
            return base.GetHashCode();
        }

        
        /// <summary>
        /// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
        /// </summary>
        /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
        /// <returns>
        /// 	<c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
        /// </returns>
        /// <exception cref="T:System.NullReferenceException">
        /// The <paramref name="obj"/> parameter is null.
        /// </exception>
        public override bool Equals(object obj){
            if(obj.GetType()==typeof(PnrPassenger)){
                PnrPassenger compare=(PnrPassenger)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        /// <summary>
        /// Descriptors the value.
        /// </summary>
        /// <returns></returns>
        public string DescriptorValue()
        {
            return this.Id.ToString();
        }
        
        /// <summary>
        /// Descriptors the column.
        /// </summary>
        /// <returns></returns>
        public string DescriptorColumn() {
            return "ID";
        }
        
        /// <summary>
        /// Gets the key column.
        /// </summary>
        /// <returns></returns>
        public static string GetKeyColumn()
        {
            return "ID";
        }   
        
        /// <summary>
        /// Gets the descriptor column.
        /// </summary>
        /// <returns></returns>        
        public static string GetDescriptorColumn()
        {
            return "ID";
        }
        #endregion
        
        #region 手动设置更新属性
        /// <summary>
        /// 手动设置更新属性.
        /// <param name="property">需要更新至数据库的属性.</param>
        /// </summary>
        public void SetUpdateProperty(IColumn property) {
            if ( !property.IsPrimaryKey&& tbl.Columns.Count(x => x.Name.ToLower() == property.Name.ToLower()) > 0 && dirtyColumns.Any(x => x.Name.ToLower() == property.Name.ToLower())){
                dirtyColumns.Add(property);
                isLoaded = true;
            }
        }
        
        

        /// <summary>
        /// 手动设置更新属性
        /// <param name="properties">需要更新至数据库的属性列表</param>
        /// </summary>
        public void SetUpdateProperty(IList<IColumn> properties)
        {
            properties.ToList().ForEach(l => {
                SetUpdateProperty(l);
            });
        }
        #endregion
        
        #region DbCommand相关
        public DbCommand GetUpdateCommand() {
            return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetInsertCommand() {
            return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        #endregion 
        
        #region 删除方法
        /// <summary>
        /// 实例数据Mapping自己删除.
        /// <param name="provider">数据.</param>
        /// </summary>
        public void Delete(IDataProvider provider) {
            _repo.Delete(KeyValue());
        }
        
        /// <summary>
        /// 实例数据Mapping自己删除.
        /// </summary>
        public void Delete() {
            Delete(_db.Provider);
        }
        
        /// <summary>
        /// 实例数据Mapping自己删除.
        /// </summary>
        public void Delete(Expression<Func< PnrPassenger, bool>> expression) {
            var repo = GetRepo();
            repo.DeleteMany(expression);
        }
        #endregion
        
        #region 修改方法
        public void Update(){
            Update(_db.Provider);
        }
        
        public void Update(IDataProvider provider){
            if(this.dirtyColumns.Count>0)
                _repo.Update(this,provider);
       }
    
        public void Add(){
            Add(_db.Provider);
        }
       
        public void Add(IDataProvider provider){
            var key=(System.Int64)KeyValue();
            //if(key==(long)0)
            //{
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            //}else{
            //    _repo.Add(this,provider);
            //}
            SetIsNew(false);
        }
        
        
        public void Save() {
            Save(_db.Provider);
        }      
        
        public void Save(IDataProvider provider) {
            if (isNew) {
                Add(provider);
            } else {
                Update(provider);
            }
            
        }
        
        /*
        public void Save(PnrPassenger Refer) {
            PnrPassenger dbClass = FirstOrDefault(l => l.Id == Refer.Id);
                dbClass.PassengerName = Refer.PassengerName;
                dbClass.IdentityNo = Refer.IdentityNo;
                dbClass.PassengerType = Refer.PassengerType;
                dbClass.Birthday = Refer.Birthday;
                dbClass.IdentityType = Refer.IdentityType;
                dbClass.TicketNoId = Refer.TicketNoId;
                dbClass.RequireId = Refer.RequireId;
            dbClass.Save();
        }
        */


        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        
        #endregion
        
        #region 静态方法
        /// <summary>
        /// 按条件获取 "未定义" 单实体 .
        /// </summary>
        /// <param name="expression">条件表达式.</param>
        /// <returns></returns>
        public static PnrPassenger FirstOrDefault(Expression<Func< PnrPassenger, bool>> expression) {
            var repo = GetRepo();
            var results = repo.Find(expression);
            PnrPassenger single = null;
            /*if (results.Count() > 0) */
            {
                single = results.FirstOrDefault();
                if(single!=null){
                    single.SetIsLoaded(true);
                    single.SetIsNew(false);
                }
            }
            return single;
        }      
        

        /// <summary>
        /// 查询所有 "未定义" 数据
        /// </summary>
        /// <returns></returns>
        public static IQueryable<PnrPassenger> All() {
            return GetRepo().GetAll();
        }

        /// <summary>
        /// 按主键加载唯一实例.
        /// </summary>
        /// <param name="key">主键值.</param>
        /// <returns></returns>
        public static PnrPassenger FirstOrDefault(object key) {
            return GetRepo().GetByKey(key);
        }


        /// <summary>
        /// 查询分页数据.
        /// </summary>
        /// <param name="sortBy">排序表达式</param>
        /// <param name="pageIndex">页次.</param>
        /// <param name="pageSize">页面大小</param>
        /// <returns></returns>
        public static PagedList<PnrPassenger> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }


        /// <summary>
        /// 查询分页数据.
        /// </summary>
        /// <param name="pageIndex">页次.</param>
        /// <param name="pageSize">页面大小</param>
        /// <returns></returns>
        public static PagedList<PnrPassenger> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);

        }
        
        /// <summary>
        /// 记录是否存在.
        /// </summary>
        /// <param name="expression">The expression.</param>
        /// <returns></returns>
        public static bool Exists(Expression<Func<PnrPassenger, bool>> expression) {
            return All().Any(expression);
        }
        
        
        /// <summary>
        /// 数据条件分页查询.
        /// </summary>
        /// <param name="expression">条件表达式.</param>
        /// <param name="pageIndex">页次.</param>
        /// <param name="pageSize">页面大小.</param>
        /// <returns></returns>
        public static IList<PnrPassenger> Find(Expression<Func<PnrPassenger, bool>> expression, int? pageIndex, int? pageSize) {
            var repo = GetRepo();
            IQueryable<PnrPassenger> query = repo.Find(expression);
            if (pageIndex.HasValue) {
                query = query.Take(pageSize ?? 10);
                query = query.Skip(((pageIndex ?? 0) - 1) * pageSize ?? 10);
            }
            return query.ToList();
        }

        /// <summary>
        /// 数据条件分页查询.
        /// </summary>
        /// <param name="expression">条件表达式.</param>
        /// <returns></returns>
        public static IList<PnrPassenger> Find(Expression<Func<PnrPassenger, bool>> expression) {
            return Find(expression, null, null);
        }
        #endregion
        
        #region CopyTo
        /// <summary>
        /// 重新复制更新列
        /// </summary>
        /// <param name="to">目标数据实体</param>
        public PnrPassenger CopyTo(PnrPassenger toEntity) {
            Type type = this.GetType();
            List<IColumn> items = type.GetProperties().Join(dirtyColumns.Where(l => !l.IsPrimaryKey), l => l.Name, o => o.PropertyName, (l, o) => o).ToList();
            foreach (IColumn c in items){
                PropertyInfo info = type.GetProperty(c.PropertyName);
                info.SetValue(toEntity, info.GetValue(this, null), null);
            }
            return toEntity;
        }
        #endregion


        
        #region 关联父级
        private PnrDetr m_FK_PNR_PASS_REFERENCE_PNR_DETR;
        /// <summary>
        /// FK_PNR_PASS_REFERENCE_PNR_DETR:未定义.
        /// <remarks>
        /// 外键名称：FK_PNR_PASS_REFERENCE_PNR_DETR
        /// 主表名称：PNR_Detr
        /// 外键字段：ID
        /// </remarks>
        /// </summary>
        [Browsable(false)]
        [XmlIgnore()]
        public PnrDetr FK_PNR_PASS_REFERENCE_PNR_DETR{
            get{
                if(m_FK_PNR_PASS_REFERENCE_PNR_DETR==null&&Context.Instance.AutoLoadRelation){
                    m_FK_PNR_PASS_REFERENCE_PNR_DETR = PnrDetr.FirstOrDefault(this.TicketNoId);
                }
                return m_FK_PNR_PASS_REFERENCE_PNR_DETR;
            }
            set{
                m_FK_PNR_PASS_REFERENCE_PNR_DETR=value;
            }
        }
        private PnrRequire m_FK_PNR_PASS_REFERENCE_PNR_REQU;
        /// <summary>
        /// FK_PNR_PASS_REFERENCE_PNR_REQU:占座PNR库.
        /// <remarks>
        /// 外键名称：FK_PNR_PASS_REFERENCE_PNR_REQU
        /// 主表名称：PNR_Require
        /// 外键字段：ID
        /// </remarks>
        /// </summary>
        [Browsable(false)]
        [XmlIgnore()]
        public PnrRequire FK_PNR_PASS_REFERENCE_PNR_REQU{
            get{
                if(m_FK_PNR_PASS_REFERENCE_PNR_REQU==null&&Context.Instance.AutoLoadRelation){
                    m_FK_PNR_PASS_REFERENCE_PNR_REQU = PnrRequire.FirstOrDefault(this.RequireId);
                }
                return m_FK_PNR_PASS_REFERENCE_PNR_REQU;
            }
            set{
                m_FK_PNR_PASS_REFERENCE_PNR_REQU=value;
            }
        }
        #endregion
        
        #region 关联子表
        #endregion
    }
} 



